package com.login.json;

import com.alibaba.fastjson2.JSON;
import com.common.exception.CodeAndMsg;
import com.common.exception.JavaSecurityException;
import com.login.domain.dto.LoginDTO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author 路亚
 * @version 0.1
 * @className Json
 * @description
 * @date 2024/12/12 15:39
 * @since jdk11
 */
public class JsonAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public JsonAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login/json", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        // 1.判断请求方式是否是post请求
        if (!"POST".equals(request.getMethod())){
            throw new JavaSecurityException(CodeAndMsg.REQUEST_METHOD_ERROR);
        }
        // 2.判断请求参数是否是json格式
        String contentType = request.getContentType();
        if (!"application/json".equals(contentType)){
            throw new JavaSecurityException(CodeAndMsg.REQUEST_PARAM_FORMAT_ERROR);
        }
        // 3.获取请求参数
        BufferedReader reader = request.getReader();
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null){
            sb.append(line);
        }
        String param = sb.toString();
        LoginDTO loginDTO = JSON.parseObject(param, LoginDTO.class);
        JsonAuthenticationToken authenticationToken = new JsonAuthenticationToken(loginDTO);
        this.authenticationDetailsSource.buildDetails(request);
        return this.getAuthenticationManager().authenticate(authenticationToken);
    }
}
